import {getInvoicesList, preinvoiceopen, inoviceheader, inoviceproducts, exportInvoice, openinvoice} from '../../services/drawback/invoice';
import {parse} from 'qs';
import { message } from 'antd';
import Constants from '../../utils/Constants';
import {downloadFile} from '../../utils/commons'
export default {
    namespace: 'invoice',
    state: {
        search: { // 查询条件
            orderno: '',
            userIds: '',
            openinvoicestatus: '0'
        },
        page: {
            page: 1,
            size: 10,
            totalRow: 0,
            totalPage: 0
        },
        list: [],
        editModel: { // 编辑视图
            showStatus: false, // 默认不显示
            confirmLoading: false, // 确认按钮loading状态
            title: '预开票', // 标题
            form: {
                defaultWidth: 1000, // 缺省宽度800
                width: 1000, // 宽度
                preamount: '',
                amountcurrency: '',
                precharge: '',
                chargecurrency: '',
                prerate: '',
                orderId: '',
                step : 0
            }
        }
    },
    reducers: {

        /**
         * 设置查询条件
         *
         * @param state
         * @param actio
         * @returns {{search}}
         */
        setSearch(state, action) {
            return {...state, search: action.payload.search};
        },

        /**
         * 是否显示
         *
         * @param state
         * @param action
         * @returns {{showStatus: (boolean|*)}}
         */
        setEditModel(state, action) {
            let payload = action.payload;

            let newState = {...state.editModel};
            if (payload.showStatus != undefined) {
                newState.showStatus = payload.showStatus;
            }
            if (payload.title != undefined) {
                newState.title = payload.title;
            }
            if (payload.confirmLoading != undefined) {
                newState.confirmLoading = payload.confirmLoading;
            }

            if(payload.type != undefined) {
                newState.type = payload.type;
            }
            if(payload.form != undefined) {
                newState.form = payload.form;
            }

            if(payload.orderId != undefined) {
                newState.orderId = payload.orderId;
            }

            if(payload.step != undefined) {
                newState.step = payload.step;
            }

            if(payload.width != undefined) {
                newState.width = payload.width;
            }

            if(payload.form != undefined) {
                newState.form = payload.form;
            }

            if(payload.step != undefined) {
                newState.step = payload.step;
            }

            return {...state, editModel: {...newState}};
        },

        /**
         * 设置数据列表
         *
         * @param state
         * @param action
         */
        setList(state, { payload }) {
            return {...state, list: payload.list, page: payload.page}
        },

        /**
         * 设置页码
         *
         * @param state
         * @param payload
         * @returns {{page: *}}
         */
        setPage(state, { payload }) {
            return {...state, page: payload.page}
        }
    },
    effects: {

        /**
         * 分页查询预开票
         * @param call
         * @param put
         * @param select
         */
        *getInvoicesList({}, {call, put, select}) {
            const search = yield select(state => state.invoice.search);
            const page = yield select(state => state.invoice.page);


            const res = yield call(getInvoicesList, {
                orderno: search.orderno,
                userIds: search.userIds,
                openinvoicestatus: search.openinvoicestatus,
                page
            });


            if (res.data.resultCode === "ok") {
                let content = res.data.content;

                yield put({
                    type: 'setList',
                    payload: {
                        list: content.list,
                        page: content.page == undefined ? Constants.DEFAULTPAGE : content.page
                    }
                });
            } else {
                message.error(res.data.errMessage);
            }
        },


        /**
         * 预开票
         * @param payload
         * @param call
         * @param put
         * @param select
         */
        *preinvoiceopen({ payload }, { call, put, select }) {
            const res = yield call(preinvoiceopen, payload);
            if (res.data.resultCode === "ok") {
                message.info("预开票成功！");
                yield put({
                    type: 'setEditModel',
                    payload: {
                        showStatus: false
                    }
                });

                yield put({
                    type: 'getInvoicesList'
                });

            } else {
                message.error(res.data.errMessage);
            }
        },


        /**
         * 根据订单获取开票资料表头信息
         * @param payload
         * @param call
         * @param put
         * @param select
         */
        *inoviceheader({ payload }, { call, put, select }) {
            const res = yield call(inoviceheader, { orderId: payload.orderId});
            if (res.data.resultCode === "ok") {
                let content = res.data.content;

                yield put({
                    type: 'inoviceproducts',
                    payload: {
                        orderId : payload.orderId,
                        form: {
                            heard : content[0],
                            type : payload.type
                        },
                    }
                });
            } else {
                message.error(res.data.errMessage);
            }
        },


        /**
         *根据订单获取开票资料具体产品信息
         * @param payload
         * @param call
         * @param put
         * @param select
         */
        *inoviceproducts({ payload }, { call, put, select }) {
            const res = yield call(inoviceproducts, { orderId: payload.orderId});

            if (res.data.resultCode === "ok") {
                let content = res.data.content;

                yield put({
                    type: 'setEditModel',
                    payload: {
                        showStatus: true,
                        confirmLoading: false,
                        title: "开票资料详情",
                        step: 1,
                        width: 1500,
                        form: {
                            heard : payload.form.heard,
                            type : payload.form.type,
                            list : content
                        }
                    }
                });

            } else {
                message.error(res.data.errMessage);
            }
        },


        /**
         * 生成开票资料
         * @param payload
         * @param call
         * @param put
         * @param select
         */
        *exportInvoice({payload}, {call, put, select}) {

            let list = payload.list;
            let orderProductDetails = [];

            if (list != null && list.length > 0) {
                for (let i = 0; i < list.length; i++) {
                    let product = {
                        id: list[i].id,
                        productmodel: list[i].productmodel,
                        invoiceremark: list[i].invoiceremark,
                    };

                    orderProductDetails.push(product);
                }
            }

            let form = {
                order: {id: payload.orderId, invoiceType: payload.invoiceType},
                orderProductDetails: orderProductDetails,
            };


            //更新发票资料
            const openinvoiceRes = yield call(openinvoice, {form});
            if (openinvoiceRes.data.resultCode === "ok") {

                //导出资料
                const res = yield call(exportInvoice, {orderId: payload.orderId, invoiceType: payload.invoiceType});
                message.info("生成开票资料成功！");
                yield put({
                    type: 'setEditModel',
                    payload: {
                        showStatus: false
                    }
                });
                yield put({
                    type: 'getInvoicesList'
                });
            } else {
                message.error(res.data.errMessage);
            }


        },


        *setInoviceproducts({payload}, {call, put, select}) {
            let record = payload.record;
            let value = payload.value.target.value;
            let type = payload.type;

            if(type == "productmodel"){
                record.productmodel = value;

            }else if(type == "invoiceremark"){
                record.invoiceremark = value;
            }

        },


        *downloadFile({payload}, {call, put, select}) {
            let type = payload.type;
            let url = payload.url;
            downloadFile(type, url);
        },


    },
    subscriptions: {
        setup({history, dispatch}) {
            return history.listen(({pathname}) => {
                if(pathname.includes('drawback/invoice')) {
                    dispatch({
                        type: 'getInvoicesList'
                    });
                }

            });
        }
    }

};
